import org.antlr.runtime.tree.*;
import org.antlr.runtime.*;

import java.util.List;

public class TypeTree extends CommonTree {
	public static final int CHAR_TYPE = 1;
	public static final int INT_TYPE = 2;
	public static final int LONG_TYPE = 3;
	public static final int FLOAT_TYPE = 4;
	public static final int DOUBLE_TYPE = 5;
	
	public int primitiveType = INT_TYPE;
	public int elementSize = 0;
	public int length = 0;

	public String llvmType = "int32";

	public TypeTree(int ttype)
	{
		super(new CommonToken(ttype));
	}

	public TypeTree(int ttype, int elementSize, int length)
	{
		super(new CommonToken(ttype));
		this.elementSize = elementSize;
		this.length = length;
	}

	public TypeTree(Token t)
	{
		super(t);
	}

	public TypeTree(TypeTree t)
	{
		super(t);
	}

	public Tree dupNode()
	{
		TypeTree t = new TypeTree(this);
		t.elementSize = this.elementSize;
		t.length = this.length;
		return t;
	}

	public void setType()
	{
		if (getToken().getType() == CParser.BASIC_TYPE)
		{
			List list = getChildren();
			for (Object o : list)
			{
				TypeTree t = (TypeTree)o;
				switch (t.getToken().getType())
				{
				case CParser.CHAR:
					this.primitiveType = CHAR_TYPE;
					this.elementSize = 1;
					this.length = 1;
					this.llvmType = "int8";
					break;
				case CParser.INT:
					this.primitiveType = INT_TYPE;
					this.elementSize = 4;
					this.length = 1;
					this.llvmType = "int32";
					break;
				}
			}
		}
		else if (getToken().getType() == CParser.POINTER)
		{
			TypeTree t = (TypeTree)getChild(0);
			t.setType();
			this.primitiveType = t.primitiveType;
			this.elementSize = 8;
			this.length = 1;
			this.llvmType = t.llvmType + "*";
		}
		else if (getToken().getType() == CParser.ARRAY)
		{
			TypeTree t = (TypeTree)getChild(0);
			ExpressionTree d = (ExpressionTree)getChild(1);
			d.evaluate();
			t.setType();
			this.primitiveType = t.primitiveType;
			this.elementSize = t.elementSize * t.length;
			this.length = (Integer)d.value;
			this.llvmType = "[ " + this.length + " x " + t.llvmType + "]";
		}
	}
}